package com.yjhb.android.sbz.activity;

import android.Manifest;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.adapter.CommentAdapter;
import com.yjhb.android.sbz.dialog.TaskTipsDialog;
import com.yjhb.android.sbz.dialog.TipsDialog;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.entity.CheckEntity;
import com.yjhb.android.sbz.entity.Comment;
import com.yjhb.android.sbz.entity.ShopInfo;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.entity.TaskStep;
import com.yjhb.android.sbz.entity.TaskSubmit;
import com.yjhb.android.sbz.entity.UserFollow;
import com.yjhb.android.sbz.enums.TaskStatus;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.mvp.task.DetailsPresenter;
import com.yjhb.android.sbz.mvp.task.DetailsView;
import com.yjhb.android.sbz.mvp.userinfo.UserInfoPresenter;
import com.yjhb.android.sbz.mvp.userinfo.UserInfoView;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.v2.mvp.presenter.NowPresenter;
import com.yjhb.android.sbz.v2.mvp.view.NowView;
import com.yjhb.android.sbz.view.MyScrollView;
import com.yjhb.android.sbz.view.TaskStepItemView;
import com.yjhb.android.sbz.view.TaskStepView;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxClipboardTool;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxSpanTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.tool.ZxTool;
import com.jojo.android.zxlib.view.CircleImageView;
import com.jojo.android.zxlib.view.EmptyRecyclerView;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.jetbrains.annotations.NotNull;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import pl.droidsonroids.gif.AnimationListener;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * 创建者 zx
 * 创建时间 2020/11/27 11:28
 */
public class TaskDetailsActivity extends BaseActivity<DetailsPresenter> implements DetailsView, TaskStepView.onItemButtonClickListener, NowView {
    private final String TAG = "TaskDetailsActivity";
    @BindView(R.id.scrollView)
    MyScrollView scrollView;
    @BindView(R.id.task_step_view)
    TaskStepView task_step_view;
    @BindView(R.id.bottom_layout)
    LinearLayout bottom_layout;
    @BindView(R.id.title_tv)
    TextView title_tv;
    @BindView(R.id.title_layout)
    View title_layout;
    @BindView(R.id.id_tv)
    TextView id_tv;
    @BindView(R.id.earned_tv)
    TextView earned_tv;
    @BindView(R.id.taskId_tv)
    TextView taskId_tv;
    @BindView(R.id.head_iv)
    CircleImageView head_iv;
    @BindView(R.id.currentStock_tv)
    TextView currentStock_tv;
    @BindView(R.id.table1_tv)
    TextView table1_tv;
    @BindView(R.id.table3_tv)
    TextView table3_tv;
    @BindView(R.id.taskTime_tv)
    TextView taskTime_tv;
    @BindView(R.id.checkTime_tv)
    TextView checkTime_tv;
    @BindView(R.id.device_tv)
    TextView device_tv;
    @BindView(R.id.task_step_tv)
    TextView task_step_tv;
    @BindView(R.id.icon_android)
    ImageView icon_android;
    @BindView(R.id.icon_iphone)
    ImageView icon_iphone;
    @BindView(R.id.money_tv)
    TextView money_tv;
    @BindView(R.id.task_remark_title)
    TextView task_remark_title;
    @BindView(R.id.task_remark)
    TextView task_remark;
    @BindView(R.id.hosting_tv)
    TextView hosting_tv;

    @BindView(R.id.submit_layout)
    ViewGroup submitLayout;
    @BindView(R.id.tips_layout)
    ViewGroup tipsLayout;
    @BindView(R.id.replace_layout)
    ViewGroup replaceLayout;
    @BindView(R.id.sign_layout)
    ViewGroup signLayout;
    @BindView(R.id.bottom_tips_tv)
    TextView bottom_tips_tv;
    @BindView(R.id.submit_tv)
    TextView submit_tv;
    @BindView(R.id.num_tv)
    TextView num_tv;
    @BindView(R.id.vip_iv)
    ImageView vip_iv;
    @BindView(R.id.replace_tv)
    TextView replaceTv;
    @BindView(R.id.sendMsg_tv)
    TextView sendMsgTv;
    @BindView(R.id.replace)
    View replace;
    @BindView(R.id.replace_iv)
    GifImageView replace_iv;
    @BindView(R.id.sendMsg)
    View sendMsg;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.follow_tv)
    TextView follow_tv;
    @BindView(R.id.copy_tv)
    TextView copy_tv;
    @BindView(R.id.modify_layout)
    FrameLayout modify_layout;
    @BindView(R.id.countdown_time_tv)
    TextView countdown_time_tv;
    @BindView(R.id.comment_empty_layout)
    View comment_empty_layout;
    @BindView(R.id.comment_emptyRecyclerView)
    EmptyRecyclerView comment_emptyRecyclerView;
    @BindView(R.id.toast_tv)
    TextView toast_tv;
    @BindView(R.id.more_comment)
    TextView more_comment;

    private String taskId;
    private Task task;
    private ArrayList<TaskStep> taskSteps;
    private TaskStep currentStep = null; //当前焦点步骤
    private int status;
    private UserInfoPresenter userInfoPresenter;
    private UserFollow userFollow;
    private CommentAdapter commentAdapter;
    private List<Comment> comments = new ArrayList<>();


    private int commentPageSize = 15;
    private int commentPageNum = 1;

    //提交订单ID，在重新编辑时用于获取值
    Integer orderId;

    int mode;
    public final static int MODE_PREVIEW = 0; //预览
    public final static int MODE_EDIT = 1; //正常编辑
    public final static int MODE_REEDIT = 2; //重新编辑
    public final static int MODE_READ = 3; //只读
    private CountDownTimer countDownTimer;

    /**
     * 换一换接口
     */
    private NowPresenter nowPresenter;
    /**
     * 换一换的缓存数据
     */
    private ArrayList<Task> changeCache = new ArrayList<>();

    /**
     * 换一换当前索引
     */
    private int replaceIndex = 0;

    @Override
    protected DetailsPresenter initPresenter() {
        return new DetailsPresenter(this);
    }

    @Override
    protected int getStatusBarResource() {
        return R.color.red_4040;
    }

    @Override
    protected boolean isImmerse() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_details2;
    }

    @Override
    protected void initUI() {
        init();
        Intent intent = getIntent();
        mode = intent.getIntExtra("mode", MODE_EDIT);
        if (mode == MODE_PREVIEW) {
            task = (Task) intent.getSerializableExtra("task");
            Object o = intent.getSerializableExtra("taskSteps");
            if (o != null) {
                taskSteps = (ArrayList<TaskStep>) o;
            }
            initPreview();
        } else {
            taskId = intent.getStringExtra("taskId");
            ArrayList<Task> temp = (ArrayList<Task>) intent.getSerializableExtra("changeCache");
            if (temp != null) {
                changeCache.clear();
                changeCache.addAll(temp);
                replaceIndex = 1;
//                showToast("为您推荐了" + temp.get(0).getName(),2500);
            }
        }
        if (mode == MODE_REEDIT) {
            orderId = intent.getIntExtra("orderId", -1);
            if (orderId == -1) {
                ZxToast.showINFOBottomToast("找不到该任务！");
                finish();
            }
        }
        if (mode == MODE_READ) {
            initPreview();
        }
    }

    private void init() {
        TextView tips = comment_empty_layout.findViewById(R.id.tips_tv);
        tips.setText("暂无更多评价");
        comment_emptyRecyclerView.setEmptyView(comment_empty_layout);
        comment_emptyRecyclerView.setNestedScrollingEnabled(false);
        comment_emptyRecyclerView.setAdapter(commentAdapter = new CommentAdapter(this));
        commentAdapter.setComments(comments);
        //用户信息
        replace_iv.setFreezesAnimation(false);
        GifDrawable gifDrawable = (GifDrawable) replace_iv.getDrawable();
        if (gifDrawable != null) {
            gifDrawable.stop();
        }
        userInfoPresenter = new UserInfoPresenter(new UserInfoView() {
            @Override
            public void onFollow() {
//                if (userFollow != null)
//                    ZxToast.showSuccessCenterToast(userFollow.isFollow() ? "已取消关注" : "已关注");
                if (task != null)
                    userInfoPresenter.getUserInfo(task.getUserId());
            }

            @Override
            public void onShopInfo(ShopInfo shopInfo) {

            }

            @Override
            public void onWait() {

            }

            @Override
            public void onSuccess(UserFollow data) {
                userFollow = data;
                updateUserInfo();
            }

            @Override
            public void onFailure(int code, String msg) {
//                ZxToast.showINFOBottomToast(msg);
            }
        });
        nowPresenter = new NowPresenter(this);

    }

    @Override
    protected void initData() {
        switch (mode) {
            case MODE_PREVIEW:
                break;
            case MODE_EDIT:
            case MODE_REEDIT:
                presenter.getDetails(taskId);
                presenter.check(taskId);
                presenter.commentList(taskId, 5, 1);
                if (DataSaveTool.isShowTaskTips() && changeCache.size() < 1) {
                    TaskTipsDialog taskTipsDialog = new TaskTipsDialog(this);
                    taskTipsDialog.show();
                }
                break;
            case MODE_READ:
                presenter.getDetails(taskId);
                presenter.commentList(taskId, 5, 1);
                break;
        }

    }


    @Override
    protected void regEvent() {
//        commentRecyclerView.setOnLoadMoreListener(this);
        task_step_view.setOnItemButtonClickListener(this);
        scrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                //动态更改title透明度
                int max = ResManager.dp() * 50;
                int a = 0;
                float b = max / 254f;
                a = (int) (scrollY * b);
                if (a > 254f) {
                    a = 0xff;
                } else if (a <= 0) {
                    a = 0;
                }
                title_layout.setBackgroundColor(Color.argb(a, 0xff, 0x40, 0x40));
            }
        });
    }


    private void showToast(CharSequence msg, long duration) {
        toast_tv.setVisibility(View.VISIBLE);
        toast_tv.setText(msg);
        ValueAnimator valueAnimator = ValueAnimator.ofInt(450, 150, 200, 150, 180, 150, 170, 150);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (toast_tv != null) {
                    if (toast_tv.getLayoutParams() instanceof FrameLayout.LayoutParams) {
                        ((FrameLayout.LayoutParams) toast_tv.getLayoutParams()).bottomMargin = ZxTool.dip2px((int) animation.getAnimatedValue());
                        toast_tv.requestLayout();
                    }
                }
            }
        });
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        Global.getInstance().getMainHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (toast_tv != null) {
                    toast_tv.setVisibility(View.GONE);
                }
            }
        }, duration + 1000);
    }

    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @Override
    public void onItemButtonClick(TaskStepItemView stepItemView, int button) {
        currentStep = stepItemView.getStep();
        if (button == TaskStepItemView.BUTTON_UPLOAD_IMG) {
            new RxPermissions(this).request(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            Tool.getPictureSelector(TaskDetailsActivity.this, 1)
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        }
                    });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> medias = (List<LocalMedia>) data.getSerializableExtra(PictureConfig.EXTRA_RESULT_SELECTION);
                if (medias != null) {
                    if (currentStep != null) {
//                        currentStep.setContent(medias.get(0).getPath());
                        task_step_view.getItemView(currentStep.getId()).setInputContent(medias.get(0).getPath());
                        task_step_view.getItemView(currentStep.getId()).refresh();
                    }
                }
            }

        }


    }

    @OnClick({R.id.submit_layout, R.id.modify_layout})
    void submit_layout(View view) {
        if (taskSteps == null) {
            ZxToast.showFAILBottomToast("任务步骤异常，请刷新后重试！");
            return;
        }
        List<TaskSubmit> submits = new ArrayList<>();
        for (TaskStep step : taskSteps) {
            if (step.getType() != 6 && step.getType() != 7) continue;

            TaskSubmit submit = new TaskSubmit();
            String inputContent = task_step_view.getItemView(step.getId()).getInputText();

            switch (step.getType()) {
                case 6:
                    if (TextUtils.isEmpty(inputContent)) {
                        ZxToast.showINFOBottomToast("您有图片信息未上传哦~");
                        return;
                    }
                    submit.setImg(true);
                    break;
                case 7:
                    if (TextUtils.isEmpty(inputContent)) {
                        ZxToast.showINFOBottomToast("\"" + step.getTitle() + "\"未填写内容哦~");
                        return;
                    }
                    submit.setImg(false);
                    break;

            }
            submit.setTitle(step.getTitle());
            submit.setContent(inputContent);
            submit.setStepId(step.getId());
            submits.add(submit);
        }
        if (submits.size() < 1) {
            ZxToast.showINFOBottomToast("没有输入信息哦~~");
            return;
        }
        if (DataSaveTool.isShowTaskSubmitTips()) {
            TipsDialog tipsDialog = new TipsDialog(this);
            tipsDialog.setTitle("提示");
            tipsDialog.setButtonVisibility(TipsDialog.TYPE_CHECK, View.VISIBLE);
            CharSequence charSequence = "请按照悬赏要求提交验证信息（切勿提交跟悬赏无关的任何一切信息）情节严重者会进行封禁冻结！";
            charSequence = ZxSpanTool.ZoomSpan(ZxSpanTool.ColorSpan(charSequence, charSequence.length() - 5, charSequence.length()
                    , Color.RED), charSequence.length() - 5, charSequence.length(), 1.5f);
            tipsDialog.setContent(charSequence);
            tipsDialog.setContentGravity(Gravity.CENTER);
            tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
                @Override
                public void onClick(int type) {
                    if (type == TipsDialog.TYPE_SUBMIT) {
                        presenter.submitTask(task.getId(), submits, mode == MODE_REEDIT || view == modify_layout ? 1 : null);
                        tipsDialog.cancel();
                    } else if (type == TipsDialog.TYPE_CANCEL) {
                        tipsDialog.cancel();
                    }
                    DataSaveTool.saveShowTaskSubmitTips(!tipsDialog.getCheckbox().isChecked());
                }
            });
            tipsDialog.show();
        } else {
            presenter.submitTask(task.getId(), submits, mode == MODE_REEDIT || view == modify_layout ? 1 : null);
        }

    }

    @OnClick(R.id.sign_layout)
    void sign_layout() {
        if (App.userInfo == null || App.userInfo.getId() == null) {
            ZxActivityTool.skipActivity(this, LoginActivity.class);
            return;
        }
        if (task == null) return;
        if (App.userInfo.getId().equals("" + task.getUserId())) {
            ZxToast.showFAILBottomToast("您不能接取自己发布的任务哦~~");
            return;
        }
        if (status == 2) {
            TipsDialog tipsDialog = new TipsDialog(this);
            tipsDialog.setContent("你曾报名过其它【" + task.getName() + "】任务，确认还能参与？" +
                    "提交同类任务将被系统记录！若是恶意重复提交将被封号处理！平台会监控每一个数据，请谨慎参与！");
            tipsDialog.setTitle("提示");
            tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
                @Override
                public void onClick(int type) {
                    tipsDialog.cancel();
                    if (type == TipsDialog.TYPE_SUBMIT) {
                        presenter.fetch(taskId);
                    }
                }
            });
            tipsDialog.show();
        } else {
            presenter.fetch(taskId);
        }
    }

    @OnClick(R.id.replace)
    void replace() {
        GifDrawable gifDrawable = (GifDrawable) replace_iv.getDrawable();
        gifDrawable.setLoopCount(1);
        gifDrawable.addAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationCompleted(int loopNumber) {

            }
        });
        gifDrawable.reset();
        if (replaceIndex < changeCache.size()) {
            presenter.getDetails(changeCache.get(replaceIndex).getId().toString());
            replaceIndex++;
        } else {
            nowPresenter.getNowTask();
        }

    }

    @OnClick(R.id.sendMsg)
    void sendMsg() {
        if (task != null) {
//            task.setTitle("简单秒审 3分钟搞定");
//            task.setRemark("简单实名认证(正规电商平台 无费用)");
//            task.setAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/pHPfugzib71I7TCIzicfBkcicaTpwEHsGav4fOaEQr7hBNIOicoSSZK7ibibictJoJjrUto4zia0ZJoXD6zLT4Mzqq2oiaA/132");
            //在创建一个URI链接时要注意给内容部分进行URL编码，防止出现奇怪的内容而导致链接无法解析。
            Tool.sendTaskMsg(this, "" + task.getUserId(), task, 2);
        }
    }

    @OnClick(R.id.follow_tv)
    void follow() {
        if (task != null && userFollow != null) {
            userInfoPresenter.follow(task.getUserId(), userFollow.isFollow() ? 2 : 1);
        }
    }

    @OnClick(R.id.copy_tv)
    void copy_tv() {
        if (task != null) {
            ZxClipboardTool.copyText(this, "" + task.getId());
            ZxToast.showSuccessBottomToast("已复制");
        }
    }

    @OnClick(R.id.more_comment)
    void more_comment() {
        Intent intent = new Intent(this, MoreCommentListActivity.class);
        intent.putExtra("taskId", taskId);
        startActivity(intent);
    }

//    @OnClick(R.id.share_tv)
//    void share() {
//        Tool.SharePopup(this, rootView);
//    }


    @OnClick(R.id.head_iv)
    void head_iv() {
        if (Tool.checkLogin(this)) {
            if (task != null)
                Tool.startUserInfoActivity(this, task.getUserId());
        }
    }

    @OnClick(R.id.title_right_tv)
    void title_right_tv() {
        Tool.showPopupRules(this, findViewById(R.id.title_right_tv));
    }

    private void updateUserInfo() {
        if (userFollow != null) {
            int vipLevel = userFollow.getVipLevel();
            vip_iv.setVisibility(View.VISIBLE);
            switch (vipLevel) {
                case 100:
                    vip_iv.setImageResource(R.mipmap.exp);
                    break;
                case 1:
                    vip_iv.setImageResource(R.mipmap.month);
                    break;
                case 2:
                    vip_iv.setImageResource(R.mipmap.season);
                    break;
                case 3:
                    vip_iv.setImageResource(R.mipmap.year);
                    break;
                case 4:
                    vip_iv.setImageResource(R.mipmap.half_year);
                    break;
                default:
                    vip_iv.setVisibility(View.GONE);
            }
            if (userFollow.isFollow()) {
                follow_tv.setBackgroundResource(R.drawable.gray_corners);
                follow_tv.setTextColor(Color.WHITE);
                follow_tv.setText("已关注");
            } else {
                follow_tv.setBackgroundResource(R.drawable.contact_shape);
                follow_tv.setTextColor(ResManager.getThemeColor());
                follow_tv.setText("+关注TA");
            }

        }
    }

    private void update() {
        if (task != null) {
            Glide.with(this).load(task.getAvatar()).apply(new RequestOptions().placeholder(R.mipmap.test_head))
                    .into(head_iv);
//            if (task instanceof )
            title_tv.setText(task.getTitle());
            taskId_tv.setText("任务编号:" + (taskId == null ? "--" : taskId));
            CharSequence earned = (task.getSuccess()) + "单";
            earned = ZxSpanTool.ZoomSpan(earned, 0, earned.length() - 1, 1.4f);
            earned_tv.setText(earned);
            currentStock_tv.setText("剩余" + task.getCurrentStock() + "单");
            table1_tv.setText(Tool.idTransformString(task.getCategoryId()));
            table3_tv.setText(task.getName());
            CharSequence host = Tool.getPrettyNumber(task.getTotalMoney()) + "元";
            host = ZxSpanTool.ZoomSpan(host, 0, host.length() - 1, 1.4f);
            hosting_tv.setText(host);
            if (task.getFetchNum() == Integer.MAX_VALUE) {
                num_tv.setText("次数限制:不限制");
            } else {
                num_tv.setText("次数限制:可做" + task.getFetchNum() + "次");
            }
            int taskTime = task.getTaskTime();
            if (taskTime > 24) {
                CharSequence c = (int) (taskTime / 24) + "天";
                c = ZxSpanTool.ZoomSpan(c, 0, c.length() - 1, 1.4f);
                taskTime_tv.setText(c);
            } else {
                CharSequence c = taskTime + "小时";
                c = ZxSpanTool.ZoomSpan(c, 0, c.length() - 2, 1.4f);
                taskTime_tv.setText(c);
            }
            int checkTime = task.getAuditTime();
            if (checkTime > 24) {
                CharSequence c = (int) (checkTime / 24) + "天";
                c = ZxSpanTool.ZoomSpan(c, 0, c.length() - 1, 1.4f);
                checkTime_tv.setText(c);
            } else {
                CharSequence c = checkTime + "小时";
                c = ZxSpanTool.ZoomSpan(c, 0, c.length() - 2, 1.4f);
                checkTime_tv.setText(c);
            }
            int device = task.getDevice();
            if (device == 0) {
                device_tv.setText("设备支持:安卓、苹果");
                task_step_tv.setText("任务步骤");
                icon_android.setVisibility(View.GONE);
                icon_iphone.setVisibility(View.GONE);
            } else if (device == 1) {
                device_tv.setText("设备支持:仅安卓");
                task_step_tv.setText("任务步骤/仅支持安卓设备");
                icon_android.setVisibility(View.VISIBLE);
                icon_iphone.setVisibility(View.GONE);
            } else if (device == 2) {
                device_tv.setText("设备支持:仅苹果");
                task_step_tv.setText("任务步骤/仅支持苹果设备");
                icon_android.setVisibility(View.GONE);
                icon_iphone.setVisibility(View.VISIBLE);
            }
            BigDecimal bigDecimal = Tool.getPrettyNumber(task.getMoney());
            money_tv.setText(ZxSpanTool.ZoomSpan(ZxSpanTool.StyleSpan("¥" + bigDecimal,
                    1, 1 + bigDecimal.toString().length(), Typeface.BOLD), 0, 1, 0.5f));
            id_tv.setText("ID:" + task.getUserId());
            if (TextUtils.isEmpty(task.getRemark())) {
                task_remark.setVisibility(View.GONE);
                task_remark_title.setVisibility(View.GONE);
            } else {
                task_remark.setVisibility(View.VISIBLE);
                task_remark_title.setVisibility(View.VISIBLE);
                task_remark.setText(task.getRemark());
            }
        }
        if (taskSteps != null) {
            task_step_view.setTask(taskSteps);
            task_step_view.refresh();
            //预览模式不允许编辑
            if (mode == MODE_PREVIEW) {
                task_step_view.setEnabled(false);
            }

        }
    }

    /**
     * 初始化预览
     */
    private void initPreview() {
        bottom_layout.setVisibility(View.GONE);
        update();
    }

    @Override
    protected void onDestroy() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        countDownTimer = null;
        super.onDestroy();
    }

    @Override
    public void onWait() {
        loadingDialog.setTipsText("正在加载...");
        loadingDialog.show();
    }

    @Override
    public void onSuccess(AddTask data) {
        loadingDialog.cancel();
        task = data.getTask();
        taskId = "" + task.getId();
        taskSteps = (ArrayList<TaskStep>) data.getSteps();
        userInfoPresenter.getUserInfo(task.getUserId());
        presenter.check(taskId);
        presenter.commentList(taskId, 5, 1);
        //更新ui
        update();
        //向UI中加值 (如果是重新编辑模式)
        if (mode == MODE_REEDIT) {
            presenter.getPutValue(orderId);
        }
    }

    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        ZxLogTool.e(TAG, msg);
        if (code != -1 && code != 403 && code != 606 && code != 604)
            ZxToast.showBottomToastLight(msg);
    }

    @Override
    public void signSuccess() {
        loadingDialog.cancel();
        ZxToast.showSuccessCenterToast("报名成功啦~ 开始做任务吧！");
        presenter.check(taskId);
    }

    @Override
    public void check(Integer state) {
        if (state == null) return;
        if (mode == MODE_READ || mode == MODE_PREVIEW) {
            bottom_layout.setVisibility(View.GONE);
            task_step_view.setEnabled(false);
            task_step_view.setSign(true);
        } else {
            bottom_layout.setVisibility(View.VISIBLE);
        }
        replace.setVisibility(View.VISIBLE);
        sendMsg.setVisibility(View.GONE);
        modify_layout.setVisibility(View.GONE);
        if (App.userInfo == null) {
            Drawable drawable = getDrawable(R.mipmap.sign_up);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            signTv.setCompoundDrawables(null, null, null, null);
            signTv.setText("还没登录，先登录");
            return;
        } else {
            Drawable drawable = getDrawable(R.mipmap.sign_up);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            signTv.setCompoundDrawables(drawable, null, null, null);
            signTv.setText("我要报名");
        }
        switch (TaskStatus.getStatus(state)) {
            case TASK_STATUS_ERR:
                tipsLayout.setVisibility(View.GONE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                task_step_view.setSign(true);
                task_step_view.setEnabled(false);
                break;
            //可接取
            case TASK_STATUS_UN:
                tipsLayout.setVisibility(View.GONE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.VISIBLE);
                task_step_view.setSign(false);
                task_step_view.setEnabled(true);
                presenter.checkOrderByTaskName(taskId);
                break;
            case TASK_STATUS_SUBMIT:
                tipsLayout.setVisibility(View.GONE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                bottom_tips_tv.setText("任务已提交");
                modify_layout.setVisibility(View.VISIBLE);
                replace.setVisibility(View.GONE);
                sendMsg.setVisibility(View.VISIBLE);
                task_step_view.setEnabled(true);
                task_step_view.setSign(true);
                presenter.lastSubmitOrder(taskId);
                break;
            case TASK_STATUS_PASS:
                tipsLayout.setVisibility(View.VISIBLE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                bottom_tips_tv.setText("任务已完成");
                task_step_view.setEnabled(false);
                task_step_view.setSign(true);
                break;
            case TASK_STATUS_TIMEOUT:
                tipsLayout.setVisibility(View.VISIBLE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                bottom_tips_tv.setText("任务已超时");
                task_step_view.setEnabled(false);
                task_step_view.setSign(true);
                break;
            case TASK_STATUS_CANCEL:
                tipsLayout.setVisibility(View.VISIBLE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                bottom_tips_tv.setText("任务已取消");
                task_step_view.setEnabled(false);
                task_step_view.setSign(true);
                break;
            case TASK_STATUS_FAIL:
                tipsLayout.setVisibility(View.VISIBLE);
                submitLayout.setVisibility(View.GONE);
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                bottom_tips_tv.setText("任务已失败");
                task_step_view.setEnabled(false);
                task_step_view.setSign(true);
                break;
            case TASK_STATUS_TAKE:
                replace.setVisibility(View.GONE);
                sendMsg.setVisibility(View.VISIBLE);
                tipsLayout.setVisibility(View.GONE);
                submitLayout.setVisibility(View.VISIBLE);
                submit_tv.setText("提交任务");
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                presenter.lastSubmitOrder(taskId);
                task_step_view.setEnabled(true);
                task_step_view.setSign(true);
                break;
            case TASK_STATUS_RESUBMIT:
                replace.setVisibility(View.GONE);
                sendMsg.setVisibility(View.VISIBLE);
                tipsLayout.setVisibility(View.GONE);
                submitLayout.setVisibility(View.VISIBLE);
                submit_tv.setText("重新提交");
                replaceLayout.setVisibility(View.VISIBLE);
                signLayout.setVisibility(View.GONE);
                presenter.lastSubmitOrder(taskId);
                task_step_view.setEnabled(true);
                task_step_view.setSign(true);
                break;

        }

    }

    @Override
    public void checkOrderByTaskName(int status) {
        this.status = status;
        if (status == 0) {

        } else if (status == 1) {
            tipsLayout.setVisibility(View.VISIBLE);
            submitLayout.setVisibility(View.GONE);
            replaceLayout.setVisibility(View.VISIBLE);
            signLayout.setVisibility(View.GONE);
            bottom_tips_tv.setText("请先完成同类任务");
            task_step_view.setEnabled(false);
            task_step_view.setSign(false);
        } else if (status == 2) {

        }
    }

    @Override
    public void onLoadComments(List<Comment> comments) {
        this.comments.clear();
        if (comments != null) {
            this.comments.addAll(comments);
        }
        if (this.comments.size() > 0) {
            more_comment.setVisibility(View.VISIBLE);
        } else {
            more_comment.setVisibility(View.GONE);
        }
        commentAdapter.notifyDataSetChanged();
    }


    /**
     * 图片上传中
     */
    @Override
    public void uploading() {
        loadingDialog.setTipsText("正在上传图片...");
    }

    /**
     * 图片上传完成
     */
    @Override
    public void uploadSuccess() {
        loadingDialog.setTipsText("正在提交数据...");
    }

    @Override
    public void submitSuccess() {
        loadingDialog.cancel();
        if (task != null && task.getAuditFast() == 1) {
//            showRapidlyCheckTips();
            ZxToast.showSuccessBottomToast("提交成功，此任务已开启极速快审，悬赏主将会在1个小时内完成审核，" +
                    "若超过1个小时未审核，系统将自动判定合格，请您耐心等待。");
        } else {
            ZxToast.showSuccessCenterToast("提交成功！等待审核通过就能拿到赏金啦~~");
        }
        presenter.check(taskId);
    }

    private void showRapidlyCheckTips() {
        CharSequence charSequence = "提交成功，此任务已开启极速快审，悬赏主将会在1个小时内完成审核，" +
                "若超过1个小时未审核，系统将自动判定合格，请您耐心等待。";
        String highlight = "1个小时内";
        int index = charSequence.toString().indexOf(highlight);
        TipsDialog tipsDialog = new TipsDialog(this);
        tipsDialog.setTitle("小提示");
        tipsDialog.setContent(ZxSpanTool.ColorSpan(charSequence, index, index + highlight.length(), Color.RED));
        tipsDialog.setSubmitText("好的");
        tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }

    @Override
    public void onPutValue(CheckEntity result) {
        loadingDialog.cancel();
        if (result != null) {
            List<TaskSubmit> submits = new Gson().fromJson(result.getContent(),
                    new TypeToken<List<TaskSubmit>>() {
                    }.getType());
            if (submits != null) {
                for (TaskSubmit submit : submits) {
                    for (TaskStep step : taskSteps) {
                        if (step.getId().equals(submit.getStepId())) {
                            TaskStepItemView itemView = task_step_view.getItemView(step.getId());
                            itemView.setInputContent(submit.getContent());
                            itemView.refresh();
                        }
                    }
                }
            }
            Date fetchDate = result.getFetchDateTime();
            if (fetchDate != null && task != null) {
                //任务限定的时间+报名的时间 = 任务结束的时间
                //任务结束的时间-当前时间 = 剩余的时间
                long time = (task.getTaskTime() * 1000 * 60 * 60) + fetchDate.getTime() - System.currentTimeMillis();
                if (time > 0) {
                    countdownTime(time);
                }
            }
        }
    }

    private void countdownTime(long time) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int hour = (int) (millisUntilFinished / 1000 / 60 / 60);
                int min = (int) ((millisUntilFinished - (hour * 1000 * 60 * 60)) / 1000 / 60);
                int second = (int) ((millisUntilFinished - (hour * 1000 * 60 * 60) - (min * 1000 * 60)) / 1000);
                String countdownTime = new StringBuilder("(倒计时:")
                        .append(hour)
                        .append("时")
                        .append(min)
                        .append("分")
                        .append(second)
                        .append("秒")
                        .append(")")
                        .toString();
                countdown_time_tv.setText(countdownTime);
            }

            @Override
            public void onFinish() {
                countdown_time_tv.setText("");
                presenter.check(taskId);
            }
        };
        countDownTimer.start();
    }

    @Override
    public void onLoadSuccess(@NotNull ArrayList<Task> data) {
        changeCache.clear();
        changeCache.addAll(data);
        replaceIndex = 0;
        if (replaceIndex < changeCache.size()) {
            presenter.getDetails(changeCache.get(replaceIndex).getId().toString());
            replaceIndex++;
        }
    }
}
